package com.onlygx.dva.web.base.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.onlygx.dva.common.entity.utils.EmailParam;
import com.onlygx.dva.common.exception.FailRequestException;
import com.onlygx.dva.common.properties.CommonEmailProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Collections;

/**
 * <p>
 *  Email 发送服务
 * </p>
 *
 * @author 高祥
 * @since 2023-07-28
 */
@Service
@RequiredArgsConstructor
public class CommonEmailService {

    final CommonEmailProperties commonEmailProperties;

    private MailAccount account;

    @PostConstruct
    public void init() {
        account = new MailAccount();
        account.setHost(commonEmailProperties.getSmtpServer());
        account.setFrom(commonEmailProperties.getUsername());
        account.setUser(commonEmailProperties.getUsername());
        account.setPass(commonEmailProperties.getPassword());
        account.setSslEnable(false);
    }

    /**
     * 发送邮件
     */
    public String sendEmailCode(String emailAddr) {
        if (!Validator.isEmail(emailAddr)) {
            throw new FailRequestException("参数错误");
        }
        String code = RandomUtil.randomNumbers(6);
        //发送验证码
        EmailParam emailParam = new EmailParam("验证码", emailAddr, "【瞳见科技】验证码" + code + ",您正在进行身份验证，请妥善保管，勿告知他人！");
        sendEmailMessage(emailParam);
        return code;
    }

    public void sendEmailMessage(EmailParam emailParam) {
        if (ObjectUtil.isNull(emailParam) || StrUtil.isEmpty(emailParam.getToAddress())) {
            return;
        }
        MailUtil.send(account, Collections.singletonList(emailParam.getToAddress()), emailParam.getSubject(), emailParam.getTextBody(), false);
    }
}
